from rest_framework import serializers  # 序列化器
from .models import *  # 导入所有的模型类
# 定义序列化器
# 模型类名+Serializer
# class StudentSerializer(serializers.Serializer): # 序列化器类
    # id = serializers.CharField(label='ID',read_only=True)  # 只读
    # name = serializers.CharField(max_length=30,label='姓名')
    # age = serializers.IntegerField(label='年龄',required=False)
    # sex = serializers.IntegerField(label='性别',required=False)
    # create_time = serializers.DateTimeField(label='创建时间',required=False)
    # update_time = serializers.DateTimeField(label='更新时间',required=False)
    # is_delete = serializers.BooleanField(default=False, label='逻辑删除',required=False)
    #
    # def create(self, validated_data):  # 字典  {'name':'zl',age:18} 拆包==>  name=zl,age=18
    #     return Student.objects.create(**validated_data)
    #
    # def update(self, instance, validated_data):  # 字典
    #     instance.name = validated_data.get('name',instance.name)
    #     instance.age = validated_data.get('age',instance.age)
    #     instance.sex = validated_data.get('sex',instance.sex)
    #     instance.save()
    #     return instance


class StudentSerializer(serializers.ModelSerializer): # 序列化器类
    class_name = serializers.CharField(source='classes.name',read_only=True)

    class Meta:
        model = Student  # 转序列化器
        # fields = '__all__'  # 映射展示所有字段
        exclude = ['is_delete']  # 不想展示的字段

        # 数据校验 数值范围
        extra_kwargs = {
            'age':{'min_value':0,'max_value':100}
        }

    # 属性级别校验
    # def validate_name(self,value):
    #     if 'mq' not in value.lower():
    #         raise serializers.ValidationError('用户名需要包含mq字符')
    #     return value

    # 对象级别校验
    def validate(self,data):  # data 字典
        if 'mq' not in data['name'].lower():
            raise serializers.ValidationError('用户名需要包含mq字符')

        if data['age']<18:
            raise serializers.ValidationError('未成年不可访问')

        return data

# 引用嵌套的学生序列化器
class StudentSerializerSimple(serializers.ModelSerializer): # 序列化器类
    class Meta:
        model = Student  # 转序列化器
        fields = ['id','name','age','sex']  # 映射展示所有字段


# 班级的序列化器
class ClassesSerializer(serializers.ModelSerializer): # 序列化器类
    # 嵌套序列化
    student_set = StudentSerializerSimple(many=True,read_only=True)
    class Meta:
        model = Classes  # 转序列化器
        # fields = '__all__'  # 映射展示所有字段
        exclude = ['is_delete']  # 不想展示的字段